#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>

/*
    要求：
    先创建管道， 进而创建子进程， 父子进程使用管道进行通信
    父进程向管道当中写“i am father”，
    子进程从管道当中读出内容, 并且打印到标准输出
*/

int main()
{
    int pipefd[2]; /* 读写 */
    int n = pipe(pipefd);
    if (n < 0)
    {
        std::cerr << "pipe fail!" << std::endl;
        exit(-1);
    }
    // pipefd[0] 读端  pipefd[1] 写端
    // 创建子进程
    pid_t id = fork();
    if (id == 0)
    {
        // child
        // 关闭写端
        close(pipefd[1]);
        char buffer[1024];
        ssize_t s = read(pipefd[0], buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s] = 0;
            std::cout << buffer << std::endl;
        }
        close(pipefd[0]);
    }
    else if (id > 0)
    {
        // father
        // 关闭读端
        close(pipefd[0]);
        const char *buffer = "i am father";
        ssize_t s = write(pipefd[1], buffer, strlen(buffer));
        if (s < 0)
        {
            std::cerr << "write fail!" << std::endl;
            close(pipefd[1]); // 关闭写端
            waitpid(id, nullptr, 0);
            exit(-3);
        }
        close(pipefd[1]);
        waitpid(id, nullptr, 0);
    }
    else
    {
        std::cerr << "fork fail!" << std::endl;
        close(pipefd[0]); // 关闭读端
        close(pipefd[1]); // 关闭写端
        exit(-2);
    }

    return 0;
}